
#include <iostream>
#include <memory>
#include <string>
#include <sstream>
#include <vector>
#include <map>

// Step 1: 定义抽象表达式
class Expression {
public:
    virtual ~Expression() = default;

    // 解释方法，传入上下文
    virtual int interpret(const std::map<std::string, int>& context) const = 0;
};

// Step 2: 定义终结符表达式 (变量和常量)
class NumberExpression : public Expression {
private:
    int number_;

public:
    explicit NumberExpression(int number) : number_(number) {}

    int interpret(const std::map<std::string, int>& context) const override {
        return number_;
    }
};

class VariableExpression : public Expression {
private:
    std::string variableName_;

public:
    explicit VariableExpression(const std::string& name) : variableName_(name) {}

    int interpret(const std::map<std::string, int>& context) const override {
        if (context.find(variableName_) != context.end()) {
            return context.at(variableName_);
        }
        throw std::runtime_error("Variable not found in context: " + variableName_);
    }
};

// Step 3: 定义非终结符表达式 (加法和减法)
class AddExpression : public Expression {
private:
    std::shared_ptr<Expression> left_;
    std::shared_ptr<Expression> right_;

public:
    AddExpression(std::shared_ptr<Expression> left, std::shared_ptr<Expression> right)
        : left_(std::move(left)), right_(std::move(right)) {}

    int interpret(const std::map<std::string, int>& context) const override {
        return left_->interpret(context) + right_->interpret(context);
    }
};

class SubtractExpression : public Expression {
private:
    std::shared_ptr<Expression> left_;
    std::shared_ptr<Expression> right_;

public:
    SubtractExpression(std::shared_ptr<Expression> left, std::shared_ptr<Expression> right)
        : left_(std::move(left)), right_(std::move(right)) {}

    int interpret(const std::map<std::string, int>& context) const override {
        return left_->interpret(context) - right_->interpret(context);
    }
};

// Step 4: 客户端代码
int main() {
    // 示例表达式：x + 10 - y
    auto x = std::make_shared<VariableExpression>("x");
    auto y = std::make_shared<VariableExpression>("y");
    auto num10 = std::make_shared<NumberExpression>(10);

    // 构建表达式树
    auto addExpr = std::make_shared<AddExpression>(x, num10);
    auto subtractExpr = std::make_shared<SubtractExpression>(addExpr, y);

    // 上下文：定义变量的值
    std::map<std::string, int> context = {{"x", 5}, {"y", 2}};

    // 解释表达式
    std::cout << "Expression result: " << subtractExpr->interpret(context) << std::endl;

    return 0;
}

